package com.fat.controller;

import com.fat.annotation.NoAdmin;
import com.fat.entity.R;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * 文件的上传与下载
 */
@Tag(name = "公共接口")
@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {


    @Value("${file.upload.path}")
    private String uploadPath;


    /**
     * 文件上传 MultipartFile file这个file要跟前端的name匹配
     * 返回文件的访问路径
     */
    @NoAdmin
    @Operation(summary = "文件上传")
    @PostMapping("/upload")
    public ResponseEntity uploadfiles(MultipartFile file, HttpServletRequest request) {
        try {
            //文件大小
            long size = file.getSize();
            //1.获取原文件名称
            String oldFileName = file.getOriginalFilename();
            //2.获取文件后缀
            String extension = oldFileName.substring(oldFileName.lastIndexOf("."));
            //3.生成新文件名称(由时间+去掉-的UUID+文件后缀组成)
            String newFileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + UUID.randomUUID().toString().replace("-", "") + extension;
            //5.文件类型
            String type = file.getContentType();
            //通过拼接的方式，拼出带有时间的路径
            String dateformat = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
            String dateDirPath = uploadPath + dateformat;
            File dateDir = new File(dateDirPath);
            //如果当前日期的文件夹不存在则创建
            if (!dateDir.exists()) dateDir.mkdirs();
            //7.文件上传
            file.transferTo(new File(dateDirPath, newFileName));
            //8.返回上传的文件路径
            String baseUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
            return R.success(baseUrl + "/upload/" + dateformat + "/" + newFileName);
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }
}
